package com.myn.myrule;

import java.util.List;
import java.util.concurrent.ThreadLocalRandom;

import com.netflix.client.config.IClientConfig;
import com.netflix.loadbalancer.AbstractLoadBalancerRule;
import com.netflix.loadbalancer.ILoadBalancer;
import com.netflix.loadbalancer.Server;

/*
**2020年7月13日--下午4:30:43
**@version:
**莫耀华:
**@Description:
*/
public class MyRandomRule extends AbstractLoadBalancerRule{
    /**
     * Randomly choose from all living servers
     * 
     * 每个机器访问5次   然后换一个结点
     */
	private int total=0;//被调用的次数
	private int currentIndex=0;//被调用服务的索引
    public Server choose(ILoadBalancer lb, Object key) {
        if (lb == null) {
            return null;
        }
        Server server = null;

        while (server == null) {
            if (Thread.interrupted()) {
                return null;
            }
            List<Server> upList = lb.getReachableServers();//获取活着的服务
            List<Server> allList = lb.getAllServers();//获取全部服务

            int serverCount = allList.size();
            if (serverCount == 0) {
                /*
                 * No servers. End regardless of pass, because subsequent passes
                 * only get more restrictive.
                 */
                return null;
            }
            /**************************************************/
//            int index = chooseRandomInt(serverCount);
//            server = upList.get(index);
            if(total<5) {
            	//如果服务调用次数少于5次就调用
            	server = upList.get(currentIndex);
            	total++;
            }else {
            	//如果服务调用次数大于5次换结点
            	total=0;
            	currentIndex++;//结点++
            	if(currentIndex>upList.size()-1) {
            		currentIndex=0;
            	}
            }
            
            
            
            /**************************************************/
            if (server == null) {
                /*
                 * The only time this should happen is if the server list were
                 * somehow trimmed. This is a transient condition. Retry after
                 * yielding.
                 */
                Thread.yield();
                continue;
            }

            if (server.isAlive()) {
                return (server);
            }

            // Shouldn't actually happen.. but must be transient or a bug.
            server = null;
            Thread.yield();
        }

        return server;

    }

    protected int chooseRandomInt(int serverCount) {
        return ThreadLocalRandom.current().nextInt(serverCount);
    }

	@Override
	public Server choose(Object key) {
		return choose(getLoadBalancer(), key);
	}

	@Override
	public void initWithNiwsConfig(IClientConfig clientConfig) {
		// TODO Auto-generated method stub
		
	}
}
